import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/record/category_list_entity.dart';
import 'package:sports_new/server/api/record_api.dart';
import 'package:sports_new/utils/utils.dart';

import '../../entity/record/team_entity.dart';
import 'channel_logic.dart';

class TeamLogic extends GetxController {
  final String? seasonTag;
  TeamLogic(this.leagueId, this.seasonTag);
  bool visible = false;
  List<CategoryListEntity>? struct;
  List<String>? header;
  List<TeamEntity>? teamAll;
  int _structIndex = 0;
  late ChannelLogic channel;
  late int leagueId;
  EasyRefreshController refreshController = EasyRefreshController();

  int get structIndex => _structIndex;

  set structIndex(int value) {
    _structIndex = value;
    update();
  }

  @override
  void onInit() {
    super.onInit();
    channel = Get.find<ChannelLogic>(tag: seasonTag);
    var currentSeason = channel.season;
    channel.addListener(() {
      if (currentSeason != channel.season) {
        getCategory();
        currentSeason = channel.season;
      }
    });
  }

  @override
  void onReady() {
    super.onReady();
    getCategory();
  }

  void getCategory() async {
    List<CategoryListEntity>? data =
      await RecordApi.getCategory(
        season: channel.season,
        seasonId: channel.seasonId,
        leagueId: leagueId,
        isTeam: true,
        recordType: channel.recordType
      );
    struct = [];
    if (data != null) {
      struct = data;
      getData();
    }
    update();
  }

  void getData({bool needLoading = true}) async {
    if (struct!.isEmpty) {
      teamAll = [];
      return;
    }
    final result = await RecordApi.getTeamData(
        channel.season, leagueId, struct![structIndex].key!,channel.recordType,channel.seasonId,
        needLoading: needLoading);
    header = result?.header;
    teamAll = result?.data?.all;
    update();
  }

  void doRefresh() {
    if(refreshController.headerState?.mode.isIdle == false) return;
    refreshController.callRefresh();
  }
}
